var express = require('express');
var router = express.Router();
const Blog = require('../connet/mongod')
const jwtUtil = require('../token/token')
// 新增
router.post('/create', async (req, res)=>{
  const insertdata = req.body.userinfo
  console.log(req.body);
  const data = await Blog.users.create(insertdata)
  res.status(200).send({data,isok:true})
})
// 删除
router.post('/delete', async function(req, res){
    const _id = req.body.id
    const data = await Blog.users.deleteOne({_id});
    res.status(200).send({data,isok:true})
  })
// 修改
router.post('/update', async function(req, res){
    const {id, username, age, sex, desc, phone,password} = req.body
    console.log(req.body);
    const data = await Blog.users.updateOne({_id:id}, {$set: {username,age,sex,desc,phone,password}});
    res.status(200).send({data,isok:true})
  })
//查询
router.post('/', async (req, res)=>{
  let username = req.query.username
  const password = req.query.password
  const headtoken = req.headers.authorization
  // console.log(req.headers, 'headtoken');
    if (headtoken) {
    tokenkeyparse = jwtUtil.parestoken(headtoken)
    console.log(tokenkeyparse, 'tokenkeyparse');
    if (tokenkeyparse == 'Token过期！') {
      res.send({errmsg: '登录态过期!请重新登录'});
    } else {
      try {
        username = tokenkeyparse.username
        const data = await Blog.users.find({username:username})
        const tokenkey = jwtUtil.settoken({username})
        res.status(200).send({data, token:tokenkey})
      } catch (error) {
        console.log(error, '错误');
      }
    }
  } else {
    try {
      const data = await Blog.users.find({username:username, password: password})
      console.log(data, 'data');
      if (!data) {
        res.status(200).send({errmsg: '账号密码错误'})
      } else {
        if (data.length > 0) {
          const tokenkey = jwtUtil.settoken({username})
          res.status(200).send({data, token:tokenkey, isok:true})
        } else {
          res.status(200).send({errmsg: '账号密码错误'})
        }
      }
    } catch (error) {
      console.log(error, '错误');
    }
  }
});
module.exports = router;
